import React, { useState, useEffect } from 'react';
import { Button, Modal, Statistic, Tooltip, message } from 'antd';
// import router from 'umi/router';
import _ from 'lodash';
import router from 'umi/router';
import styles from './index.less';
import * as api from '@/services/ValueApprovelMgr';
import * as apis from '@/services/SystemMgr';
import * as alterationUtils from '../utils/alteration';
import { utils, BaseTable, DifferenceDisplayer } from '@/components/BaseTable';
import { showConfirm } from '@/utils/utils';
import PageEmpty from '@/components/PageEmpty';

const Aletratinon = props => {
  const { visible, item, handleCancel } = props;
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [messageInfo, setMessageInfo] = useState('加载中...');
  const [treeData, setTreeData] = useState([]);
  const [versionState, setVersionState] = useState('');
  const [instanceId, setInstanceId] = useState('');
  const titleTree = [
    {
      name: '项目树',
      key: 'name',
      colspan: 1,
      rowspan: 3,
    },
    {
      name: '变更类型',
      key: 'changeType',
      colspan: 1,
      rowspan: 3,
    },
    {
      name: '变更详情',
      key: 'changeDetail',
      colspan: 1,
      rowspan: 3,
    },
    {
      name: '变更前',
      key: 'beforValue',
      rowspan: 1,
      colspan: 1 * 2,
    },
    {
      name: '变更后',
      key: 'afterValue',
      rowspan: 1,
      colspan: 1 * 2,
    },
    {
      name: '差异',
      key: 'difference',
      rowspan: 1,
      colspan: 1 * 2,
    },
  ];
  const headerRenderer = utils.getHeaderRenderer(titleTree, 1);
  useEffect(() => {
    if (visible) {
      setMessageInfo('加载中...');
      if (item && Object.keys(item).length > 0) {
        const { id, taskName } = item;
        apis.noticeAgencyInfoCompareToUsingGET({ params: { noticeId: id } }).then(result => {
          if (
            result &&
            result.code * 1 === 1 &&
            result.data.compareVOS &&
            result.data.compareVOS.length > 0
          ) {
            setExpandedRowKeys(alterationUtils.getExpandedRowKeys(result.data.compareVOS));
            setTreeData(alterationUtils.buildTree(result.data.compareVOS));
          } else {
            setMessageInfo(`${taskName} -- 无法获取对比结果`);
          }
          setInstanceId(result.data.instanceId);
          setVersionState(result.data.versionState);
        });
      } else {
        setMessageInfo('暂无待办详情信息');
      }
    }
  }, [visible]);

  const getFixedColumns = items => {
    const fixedColumns = [];
    if (items && items.length > 0) {
      const differenceValue = [
        {
          key: 'Num',
          precision: 0,
          headerRenderer: (
            <div>
              <div>套数/车位数</div>
            </div>
          ),
        },
        {
          key: 'Area',
          precision: 2,
          headerRenderer: (
            <div>
              <div>面积</div>
            </div>
          ),
        },
      ];
      fixedColumns.push(
        {
          key: 'name',
          dataKey: 'name',
          title: '',
          width: 260,
          frozen: 'left',
        },
        {
          key: 'changeType',
          dataKey: 'changeType',
          title: '',
          width: 200,
          cellRenderer: data => (
            <Tooltip
              placement="topLeft"
              title={
                <div>
                  {data.rowData.detailList
                    ? data.rowData.detailList.map((v, i) => (
                        <li key={`${v.changeType + i}`}>{`${i + 1}. ${v.changeType}`}</li>
                      ))
                    : null}
                </div>
              }
            >
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                <div>
                  {data.rowData.detailList && data.rowData.detailList.length
                    ? `${data.rowData.detailList.length > 1 ? '1、' : ''}${
                        data.rowData.detailList[0].changeType
                      }${data.rowData.detailList.length > 1 ? '...' : ''}`
                    : ''}
                </div>
              </div>
            </Tooltip>
          ),
        },
        {
          key: 'changeDetail',
          dataKey: 'changeDetail',
          title: '',
          width: 200,
          cellRenderer: data => (
            <Tooltip
              placement="topLeft"
              title={
                <div>
                  {data.rowData.detailList
                    ? data.rowData.detailList.map((v, i) => (
                        <li key={`${v.changeDetail + i}`}>{`${i + 1}. ${v.changeDetail}`}</li>
                      ))
                    : null}
                </div>
              }
            >
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                <div>
                  {data.rowData.detailList && data.rowData.detailList.length
                    ? `${data.rowData.detailList.length > 1 ? '1、' : ''}${
                        data.rowData.detailList[0].changeDetail
                      }${data.rowData.detailList.length > 1 ? '...' : ''}`
                    : ''}
                </div>
              </div>
            </Tooltip>
          ),
        },
        {
          key: 'changeBeforeNum',
          dataKey: 'changeBeforeNum',
          title: '',
          precision: 0,
          width: 100,
          align: 'right',
          headerRenderer: () => (
            <div>
              <div>
                套数/车位数 <div>(套/个)</div>
              </div>
            </div>
          ),
          cellRenderer: data => {
            const { rowData } = data;
            return <Statistic value={rowData.changeBeforeNum ? rowData.changeBeforeNum : 0} />;
          },
        },
        {
          key: 'changeBeforeArea',
          dataKey: 'changeBeforeArea',
          title: '',
          precision: 2,
          width: 100,
          align: 'right',
          headerRenderer: () => (
            <div>
              <div>
                面积 <div>(平米)</div>
              </div>
            </div>
          ),
          cellRenderer: data => {
            const { rowData } = data;
            // precision={}
            return (
              <Statistic
                precision={2}
                value={rowData.changeBeforeArea ? rowData.changeBeforeArea : 0}
              />
            );
          },
        },
        {
          key: 'changeAfterNum',
          dataKey: 'changeAfterNum',
          title: '',
          precision: 0,
          width: 100,
          align: 'right',
          headerRenderer: () => (
            <div>
              <div>
                套数/车位数 <div>(套/个)</div>
              </div>
            </div>
          ),
          cellRenderer: data => {
            const { rowData } = data;
            // precision={}
            return <Statistic value={rowData.changeAfterNum ? rowData.changeAfterNum : 0} />;
          },
        },
        {
          key: 'changeAfterArea',
          dataKey: 'changeAfterArea',
          title: '',
          precision: 2,
          width: 100,
          align: 'right',
          headerRenderer: () => (
            <div>
              <div>
                面积 <div>(平米)</div>
              </div>
            </div>
          ),
          cellRenderer: data => {
            const { rowData } = data;
            // precision={}
            return (
              <Statistic
                precision={2}
                value={rowData.changeAfterArea ? rowData.changeAfterArea : 0}
              />
            );
          },
        },
      );

      // 差异值
      differenceValue.forEach(v => {
        fixedColumns.push({
          key: v.key,
          dataKey: v.key,
          width: 200,
          headerRenderer: () => v.headerRenderer,
          dataGetter: ({ rowData }) => {
            const value = rowData[`changeAfter${v.key}`] - rowData[`changeBefore${v.key}`];
            const percentage =
              rowData[`changeBefore${v.key}`] * 1 !== 0
                ? ((rowData[`changeAfter${v.key}`] - rowData[`changeBefore${v.key}`]) /
                    rowData[`changeBefore${v.key}`]) *
                  100
                : 100;
            return {
              value: _.toNumber(`${value}`.replace('%', '')),
              percentage: _.toNumber(`${percentage}`.replace('%', '')),
            };
          },
          cellRenderer: <DifferenceDisplayer precision={v.precision} />,
        });
      });
    }
    return fixedColumns;
  };

  // 手动调价
  const handleProcessingMode = () => {
    showConfirm(
      async () => {
        const response = await apis.updateManualPriceUsingPOST({
          params: { noticeId: props.item.id },
        });
        if (response?.code === 1) {
          message.success(response.message, 1, () => {
            handleCancel();
            router.push(
              `/ValueManage/PriceManage/${props.match.params.level1}/${props.match.params.level2}/${props.match.params.project}/${props.match.params.stage}/${response?.data?.versionType}/${response?.data?.versionId}`,
            );
          });
        }
      },
      '是否继续手动调价？',
      '确认后手动创建新的货值填报版本',
    );
  };

  // 作废流程
  const handleInvalidProcess = id => {
    showConfirm(
      async () => {
        const response = await api.endFlowUsingPUT({ params: { instanceId: id } });
        if (response?.code === 1) {
          message.success(response.message, 1, () => {
            handleCancel();
            window.location.reload();
          });
        }
      },
      '是否要废弃该流程?',
      '确定后将作废该流程',
    );
  };

  const attribute = {
    wrapClassName: styles.aletratinon,
    title: '版本变动消息提醒',
    width: '90%',
    visible,
    centered: true,
    onCancel: () => handleCancel(),
    footer: (
      <div>
        <Button
          type="primary"
          onClick={() => handleProcessingMode()}
          disabled={!(visible && versionState !== 'approved')}
        >
          手动调价
        </Button>
        {versionState && versionState === 'approved' ? (
          <>
            <Button type="primary" onClick={() => handleInvalidProcess(instanceId)}>
              废弃流程
            </Button>
            <Button onClick={() => handleCancel()}>继续</Button>
          </>
        ) : null}
      </div>
    ),
  };

  return (
    <Modal {...attribute}>
      {visible && !_.isEmpty(treeData) ? (
        <>
          <span>
            当前主数据面积版本/楼栋计划版本已发生变更，需根据变更自动生成价格版本或新建版本手动调价！
          </span>
          <BaseTable
            subtractHeight="250px"
            headerHeight={[30, 60]}
            expandColumnKey="name"
            headerRenderer={headerRenderer}
            defaultExpandedRowKeys={expandedRowKeys}
            fixedColumns={getFixedColumns(treeData)}
            treeData={treeData}
          />
        </>
      ) : (
        <div style={{ height: '400px' }}>
          <PageEmpty emptyTitle={messageInfo} />
        </div>
      )}
    </Modal>
  );
};

export default Aletratinon;
